package org.aristotle.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.aristotle.demo.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.aristotle.common.utils.AristotleBeanUtils;
import org.aristotle.demo.model.entity.Category;
import org.aristotle.demo.mapper.CategoryMapper;
import org.aristotle.demo.service.ICategoryService;
import org.aristotle.demo.model.vo.CategoryVO;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Autowired
    private IBookService bookService;

    @Override
    public Page<CategoryVO> queryPageList(Long id, String name, Integer current, Integer size) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper();

        if (id != null) {
            queryWrapper.eq("id",id);
        }

        if (!StringUtils.isBlank(name)) {
            queryWrapper.like("name",name);
        }

        Page<Category> page = this.page(new Page<Category>(current,size), queryWrapper);

        // 转为VO
        Page<CategoryVO> result = AristotleBeanUtils.transitionBean(page, Page<CategoryVO>::new);
        result.setRecords(AristotleBeanUtils.copyListProperties(page.getRecords(),CategoryVO::new));
        return result;
    }

    @Override
    public CategoryVO getById(Long id) {
        Category category = this.baseMapper.selectById(id);
        CategoryVO categoryVO = AristotleBeanUtils.transitionBean(category, CategoryVO::new);
        return categoryVO;
    }

    @Override
    @Transactional
    public Boolean removeById(Long id) {
        bookService.removeCategoryId(id);
        return super.removeById(id);
    }
}
